<template>
  <!--  私聊 -->
  <div class="wrapper">
    <Header></Header>
    <ul>
      <li v-for="item in privateDetail">
        <ChatItem
          v-if="fromUserInfo.id === item.from_user"
          :img="item.avator"
          me="true"
          :msg="item.message"
          :name="item.name"
          :time="item.time"
        ></ChatItem>
        <ChatItem
          v-else
          :img="item.avator"
          :msg="item.message"
          :name="item.name"
          :time="item.time"
        ></ChatItem>
      </li>
    </ul>
    <div class="input-msg">
      <textarea
        v-model="inputMsg"
        @keydown.enter.prevent="sendMessage"
        ref="message"
      ></textarea>
      <p class="btn" :class="{ enable: inputMsg != '' }" @click="sendMessage">
        {{ btnInfo }}
      </p>
    </div>
  </div>
</template>

<script>
import Header from "./Header.vue";
import ChatItem from "./ChatItem.vue";
import { private_detail, private_save_msg } from "@/api/api";
import jwtDecode from "jwt-decode";
import { toNomalTime } from "./transformTime";
export default {
  components: {
    Header,
    ChatItem
  },

  data() {
    return {
      inputMsg: "",
      privateDetail: [], //私聊相关
      toUserInfo: {
        //被私聊者
        to_user: "",
        status: ""
      },
      fromUserInfo: {}, //用户自己
      btnInfo: "发送"
    };
  },
  watch: {
    privateDetail() {
      this.refresh();
    }
  },

  methods: {
    //获取数据库的消息
    getPrivateMsg() {
      private_detail(this.toUserInfo.to_user)
        .then(res => {
          console.log(res)
          this.privateDetail = res.data;
          if (this.privateDetail.length === 0) return;
          this.privateDetail.forEach(element => {
            element.time = toNomalTime(element.time);
            element.message = element.message.split(":")[1];
          });
        })
        .catch(e => {
          console.log(e);
        });
    },
    //发送信息
    sendMessage() {
      if (this.inputMsg.trim() === "") return;
      this.sendMsgBySocket();
      this.saveMsgByDB();
    },
    //用socket发消息
    sendMsgBySocket() {
      const data = {
        from_user: this.fromUserInfo.id, //自己的id
        to_user: this.toUserInfo.to_user, //对方id
        name: this.fromUserInfo.user, //自己的昵称
        message: this.inputMsg, //消息内容
        type: "private",
        status: "1", //是否在线 0为不在线 1为在线
        time: Date.parse(new Date()) / 1000 //时间
      };
      socket.emit("sendPrivateMsg", data);
      // this.$store.commit('updateListMutation', data);
    },
    //用数据库存消息
    saveMsgByDB() {
      const data = {
        from_user: this.fromUserInfo.id, //自己的id
        to_user: this.toUserInfo.to_user, //对方的id
        name: this.fromUserInfo.user, //自己的昵称
        message: this.inputMsg, //消息内容
        status: "1", //是否在线 0为不在线 1为在线
        time: Date.parse(new Date()) / 1000 //时间
      };
      // 存此条私聊信息到数据库
      private_save_msg(data)
        .then(res => {
          this.inputMsg = "";
          // 存此条私聊信息到本地
          data.time = toNomalTime(data.time);
          console.log("saveMsgByDBdata", data);
          this.privateDetail.push(data);
        })
        .catch(e => {
          console.log(e);
          this.$notify("消息发送失败");
        });
    },
    // 获取socket消息
    getMsgBySocket() {
      socket.removeAllListeners("getPrivateMsg");
      socket.on("getPrivateMsg", data => {
        console.log("聊天内获取私聊消息", data);
        //如果收到的soket信息不是发给自己的 放弃这条soket 没必要了 因为私聊是点对点发送的
        // if(data.to_user != this.fromUserInfo.user_id) return
        //如果收到的soket信息不是来自当前聊天者 写入首页信息列表 并return

        // console.log(data.from_user, '!=', this.toUserInfo.to_user)
        // 	//soket信息不是来自当前聊天者 有未读提示
        if (data.from_user != this.toUserInfo.to_user) {
          data.chatOfNow = false;
          return;
        } else {
          data.chatOfNow = true;
        }
        //本地添加此条信息
        this.privateDetail.push(data);
      });
    },
    // 消息置底
    refresh() {
      setTimeout(() => {
        window.scrollTo(0, document.body.scrollHeight + 10000);
      }, 0);
    }
  },
  created() {
    this.toUserInfo.to_user = this.$route.params.id || 22;
    this.fromUserInfo = jwtDecode(localStorage.getItem("token"));
    this.getPrivateMsg();
    this.getMsgBySocket();
  }
};
</script>

<style lang="stylus" scoped>
  .wrapper {
    // height: 100vh;
    padding-top: 0.6rem;
    z-index: 1

    ul {
      width: 100%;
      padding-bottom: 1.6rem;
      display: flex;
      display: -webkit-flex;
      flex-direction: column;

      li {
        list-style-type: none;
      }
    }

    .input-msg {
      height: 0.46rem;
      position: fixed;
      bottom: 0.03rem;
      display: flex;
      display: -webkit-flex;
      /* Safari */
      width: 100%;
      z-index: 999;

      textarea {
        width: 87.8%;
        margin: 0 0.06rem;
        padding-top: 0.07rem;
        padding-left: 0.06rem;
        border-radius: 0.02rem;
        outline: none;
        resize: none;
        border: none;
        overflow-y: hidden;
        font: 0.16rem / 0.18rem 'Microsoft Yahei';
      }

      p.btn {
        font-size: 0.2rem;
        display: flex;
        display: -webkit-flex;
        /* Safari */
        align-items: center;
        justify-content: center;
        text-align: center;
        margin-right: 0.06rem;
        height: 100%;
        width: 11%;
        background: #ccc;
        color: white;
        border-radius: 0.02rem;
        cursor: not-allowed;
        font-family: 'Microsoft Yahei';

        &.enable {
          background: #1E90FF;
          cursor: pointer;
        }
      }
    }
  }
</style>
